package com.zboin.interview150;

import java.util.Arrays;
import java.util.List;

/** Normal
 * 给定一个含有 n 个正整数的数组和一个正整数 target 。
 *
 * 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr] ，并返回其长度。如果不存在符合条件的子数组，返回 0 。
 *
 *
 *
 * 示例 1：
 *
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 * 解释：子数组 [4,3] 是该条件下的长度最小的子数组。
 * 示例 2：
 *
 * 输入：target = 4, nums = [1,4,4]
 * 输出：1
 * 示例 3：
 *
 * 输入：target = 11, nums = [1,1,1,1,1,1,1,1]
 * 输出：0
 *
 *
 * 提示：
 *
 * 1 <= target <= 109
 * 1 <= nums.length <= 105
 * 1 <= nums[i] <= 104
 *
 *
 * 进阶：
 *
 * 如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。
 */
public class Course209 {

    public static void main(String[] args) {

        List<Result> list = List.of(
                new Result(new int[]{2,3,1,2,4,3}, 7, 2),
                new Result(new int[]{1,4,4}, 4, 1),
                new Result(new int[]{1,1,1,1,1,1,1,1}, 11, 0),
                new Result(new int[]{12,28,83,4,25,26,25,2,25,25,25,12}, 213, 8)
        );

        Course209 solution = new Course209();
        list.forEach(item -> {
            int result = solution.minSubArrayLen(item.target, item.nums);
            System.out.println(item + ", result: " + result + " " + (result == item.expected ? "√": "X"));
        });
    }

    /**
     * 滑动窗口
     */
    public int minSubArrayLen(int target, int[] nums) {
       int l = 0, r = 0, sum = 0, min = Integer.MAX_VALUE;
       while (r < nums.length) {
           sum += nums[r];
           while (sum >= target) {
               min = Math.min(min, r - l);
               sum -= nums[l++];
           }
           r++;
       }

       return min == Integer.MAX_VALUE ? 0 : min + 1;
    }

    /**
     * 暴力解法，超时
     */
    public int minSubArrayLenForce(int target, int[] nums) {
        int len = nums.length;
        int[] sums = new int[len + 1];
        sums[0] = 0;
        for (int i = 1; i < len; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }

        int min = Integer.MAX_VALUE;
        for (int i = 0; i < len; i++) {
            int s = sums[i] + target;
            int n = Arrays.binarySearch(sums, s);
            if (n < 0) {

            }
            min = Math.min(min, n);
        }

        return min == Integer.MAX_VALUE ? 0 : min + 1;
    }

    private static class Result {
        int[] nums;
        int target;
        int expected;

        public Result(int[] nums, int target, int expected) {
            this.nums = nums;
            this.target = target;
            this.expected = expected;
        }

        @Override
        public String toString() {
            return "nums=" + Arrays.toString(nums) +
                    ", target=" + target +
                    ", expected=" + expected;
        }
    }
}
